<template>
	<AbnormalTemplate
		class="alarminfo-config"
		:treeData="treeData"
		@treeHandle="treeHandle"
		:showTimeLinePiker="false"
	>
		<div slot="rightBtn">
			&emsp;<el-button
				type="primary"
				icon="el-icon-plus"
				@click="openDialog"
				>新增</el-button
			>
		</div>
		<Table
			:tableData="tableData"
			:tableHead="tableHead"
			:propKey="{ prop: 'id', label: 'name' }"
			:isUseSlot="false"
			:page="listQuery.page"
			:limit="listQuery.limit"
			v-loading="listLoading"
			@handleEdit="handleEdit"
		>
			<template slot="tool" slot-scope="{ data }">
				<el-button
					style="padding:3px;"
					icon="el-icon-document"
					@click="handleEdit(data.row)"
					type="text"
					>编辑</el-button
				>
				<el-button
					style="color:red;padding:3px;"
					icon="el-icon-delete"
					type="text"
					@click="delet(data.row)"
					>删除</el-button
				>
			</template>
		</Table>
		<Pagination
			v-show="total > 0"
			:total="total"
			:page.sync="listQuery.page"
			:limit.sync="listQuery.limit"
			@pagination="getList"
		></Pagination>
		<form-tem
			:info="{ title: '异常监测配置', width: '70%', top: '5%' }"
			:formList="formList"
			@submit="submit"
			ref="formDelg"
			@onClose="closed"
			@change="changeSource"
		></form-tem>
	</AbnormalTemplate>
</template>
<script>
import AbnormalTemplate from "@/template/abnormal.temp.vue";
import Table from "@/components/Table";
import Pagination from "@/components/Pagination"; // 分页
import VForm from "@/components/luyiming/VueEleForm/index.vue";
import {
	getAbnormalSurveyList,
	InsertAlarmInfoSetInfo,
	UpdateAlarmInfoSetInfo,
	getAlarmInfoSetInfo,
	getMonitorObject,
	getAlarmType
} from "@/api/RCIM/RCIM-systemConfig";
import { getUseSourceDeviceData } from "@/api/RCIM/RCIM-archives";
import moment from "moment";
import formTem from "@/template/form.temp";
import { deepClone } from "../../utils";
import { cloneDeep } from "lodash";
import { isArray } from "../../utils/validate";
import { validateFormNumber, validateFormInt } from "@/utils/validateForm";
import { deleteAlarmInfoSetInfo } from "@/api/RCIM/RCIM-delet";
export default {
	name: "KdHistoryData",
	components: { formTem, AbnormalTemplate, Table, Pagination, VForm },
	data() {
		return {
			treeData: {},
			total: 5,
			listLoading: true,
			listQuery: {
				page: 1,
				limit: 10
				// importance: undefined,
				// title: undefined,
				// type: undefined,
				// sort: '+id'
			},
			dialogFormVisible: false,
			enterpriseData: [],
			enterpriseList: [],
			tableData: [],
			tableHead: [
				{
					id: "enterprise",
					name: "企业",
					width: ""
				},
				{
					id: "alarmFactor",
					name: "报警因子",
					align: "center",
					width: ""
				},
				{
					id: "alarmType",
					name: "报警类型",
					align: "center",
					width: ""
				},
				{
					id: "alarmDescribe",
					name: "报警描述",
					align: "left",
					width: ""
				},
				{
					id: "alarmValue",
					name: "值",
					align: "center",
					width: ""
				},
				{
					id: "operate",
					name: "操作",
					align: "center",
					width: ""
				}
			],
			formIndex: 0,
			editInfo: {},
			formList: [
				{
					list: [
						{
							type: "select",
							width: "35%",
							label: "企业",
							placeholder: "请输入",
							moduleKey: "enterprise",
							children: "option",
							optionsType: {
								id: "id",
								label: "name"
							},
							options: []
						},
						{
							type: "select",
							width: "35%",
							labelWidth: "200px",
							label: "用源设备",
							placeholder: "请输入",
							moduleKey: "useSourceDevice",
							children: "option",
							fetch: getUseSourceDeviceData,
							fetchTimes: Infinity,
							options: [],
							disFetch: true,
							query: {
								id: "",
								page: 1,
								limit: 1000,
							},
							validate: function() {
								return [
									{
										required: true,
										message: "请选择用源设备",
										trigger: "blur"
									}
								];
							}
						},
						{
							width: "29%"
						},
						{
							type: "select",
							width: "35%",
							label: "报警类型",
							placeholder: "请输入",
							moduleKey: "alarmType",
							children: "option",
							fetch: getAlarmType,
							options: []
						},
						{
							type: "input",
							width: "35%",
							labelWidth: "200px",
							label: "报警触发延迟（秒）",
							placeholder: "请输入",
							moduleKey: "alarmDelay",
							validate: function() {
								return [
									{
										validator: validateFormInt,
										trigger: "blur"
									}
								];
							}
						},
						{
							width: "30%"
						}
					],
					title: "报警信息设置"
				},
				{
					list: [
						{
							type: "select",
							label: "报警因子",
							width: "23%",
							placeholder: "请输入",
							moduleKey: "alarmFactor_0",
							children: "option",
							fetch: getMonitorObject,
							fetchTimes: Infinity,
							options: []
						},
						{
							type: "select",
							label: "条件",
							width: "23%",
							placeholder: "请输入",
							moduleKey: "condition_0",
							children: "option",
							options: [
								{
									label: ">",
									value: ">"
								},
								{
									label: ">=",
									value: ">="
								},
								{
									label: "=",
									value: "="
								},
								{
									label: "<",
									value: "<"
								},
								{
									label: "<=",
									value: "<="
								}
							]
						},
						{
							type: "input",
							label: "值",
							width: "23%",
							placeholder: "请输入",
							moduleKey: "value_0",
							validate: function() {
								return [
									{
										required: true,
										message: "请选择用源设备",
										trigger: "blur"
									},
									{
										validator: validateFormNumber,
										trigger: "blur"
									}
								];
							}
						},
						{
							type: "select",
							label: "关联逻辑",
							labelWidth: "100px",
							width: "30.9%",
							placeholder: "请输入",
							moduleKey: "relat_0",
							children: "option",
							after: {
								width: "36%",
								content: this.renderBtn3
							},
							options: [
								{
									label: "或",
									value: "||"
								},
								{
									label: "且",
									value: "&&"
								}
							]
						}
					],
					title: "报警条件"
				},
				{
					list: [
						{
							type: "input",
							width: "92%",
							typeProp: "textarea",
							labelPosition: "left",
							labelWidth: "170px",
							label: "报警描述",
							placeholder: "请输入",
							disabled: true,
							moduleKey: "alarmDescribe",
							validate: function() {
								return [
									{
										required: true,
										message: "请先添加报警描述",
										trigger: "blur"
									}
								];
							}
						},
						{
							width: "92%",
							type: "switch",
							label: "连续报警设置",
							labelPosition: "left",
							labelWidth: "170px",
							placeholder: "请选择",
							moduleKey: "continueAlarm",
							defaultValue: 0,
							activeValue: 1,
							inactiveValue: 0
						},
						{
							type: "input",
							width: "42%",
							label: "连续报警通知间隔（秒）",
							labelPosition: "left",
							labelWidth: "170px",
							placeholder: "请输入",
							moduleKey: "noticeInterval",
							validate: function() {
								return [
									{
										validator: validateFormInt,
										trigger: "blur"
									}
								];
							}
						}
					],
					title: "报警信息"
				}
			],
		};
	},
	mounted() {},
	created() {},
	methods: {
		/**
		 * @desc 删除数据
		 * @param {Object} row 表格行数据
		 */
		delet(row) {
			this.$confirm("确认要删除吗？")
				.then(_ => {
					deleteAlarmInfoSetInfo(row.id).then(res => {
						if (res.code === 200) {
							this.getList();
							return this.$message({
								type: "success",
								message: "删除成功"
							});
						}
						return this.$message({
							type: "error",
							message: "删除失败"
						});
					});
				})
				.catch(_ => {});
		},
		/**
		 * @desc 初始化表单
		 */
		initForm() {
			this.formList = [
				{
					list: [
						{
							type: "select",
							width: "35%",
							label: "企业",
							placeholder: "请输入",
							moduleKey: "enterprise",
							children: "option",
							optionsType: {
								id: "id",
								label: "name"
							},
							options: this.enterpriseList
						},
						{
							type: "select",
							width: "35%",
							labelWidth: "200px",
							label: "用源设备",
							placeholder: "请输入",
							moduleKey: "useSourceDevice",
							children: "option",
							fetch: getUseSourceDeviceData,
							fetchTimes: Infinity,
							options: [],
							disFetch: true,
							query: {
								id: ""
							},
							validate: function() {
								return [
									{
										required: true,
										message: "请选择用源设备",
										trigger: "blur"
									}
								];
							}
						},
						{
							width: "29%"
						},
						{
							type: "select",
							width: "35%",
							label: "报警类型",
							placeholder: "请输入",
							moduleKey: "alarmType",
							children: "option",
							fetch: getAlarmType,
							options: []
						},
						{
							type: "input",
							width: "35%",
							labelWidth: "200px",
							label: "报警触发延迟（秒）",
							placeholder: "请输入",
							moduleKey: "alarmDelay",
							validate: function() {
								return [
									{
										validator: validateFormInt,
										trigger: "blur"
									}
								];
							}
						},
						{
							width: "30%"
						}
					],
					title: "报警信息设置"
				},
				{
					list: [
						{
							type: "select",
							label: "报警因子",
							width: "23%",
							placeholder: "请输入",
							moduleKey: "alarmFactor_0",
							children: "option",
							fetch: getMonitorObject,
							fetchTimes: Infinity,
							options: []
						},
						{
							type: "select",
							label: "条件",
							width: "23%",
							placeholder: "请输入",
							moduleKey: "condition_0",
							children: "option",
							options: [
								{
									label: ">",
									value: ">"
								},
								{
									label: ">=",
									value: ">="
								},
								{
									label: "=",
									value: "="
								},
								{
									label: "<",
									value: "<"
								},
								{
									label: "<=",
									value: "<="
								}
							]
						},
						{
							type: "input",
							label: "值",
							width: "23%",
							placeholder: "请输入",
							moduleKey: "value_0",
							validate: function() {
								return [
									{
										required: true,
										message: "请选择用源设备",
										trigger: "blur"
									},
									{
										validator: validateFormNumber,
										trigger: "blur"
									}
								];
							}
						},
						{
							type: "select",
							label: "关联逻辑",
							labelWidth: "100px",
							width: "30.9%",
							placeholder: "请输入",
							moduleKey: "relat_0",
							children: "option",
							after: {
								width: "36%",
								content: this.renderBtn3
							},
							options: [
								{
									label: "或",
									value: "||"
								},
								{
									label: "且",
									value: "&&"
								}
							]
						}
					],
					title: "报警条件"
				},
				{
					list: [
						{
							type: "input",
							width: "92%",
							typeProp: "textarea",
							labelPosition: "left",
							labelWidth: "170px",
							label: "报警描述",
							placeholder: "请输入",
							disabled: true,
							moduleKey: "alarmDescribe",
							validate: function() {
								return [
									{
										required: true,
										message: "请先添加报警描述",
										trigger: "blur"
									}
								];
							}
						},
						{
							width: "92%",
							type: "switch",
							label: "连续报警设置",
							labelPosition: "left",
							labelWidth: "170px",
							placeholder: "请选择",
							moduleKey: "continueAlarm",
							defaultValue: 0,
							activeValue: 1,
							inactiveValue: 0
						},
						{
							type: "input",
							width: "42%",
							label: "连续报警通知间隔（秒）",
							labelPosition: "left",
							labelWidth: "170px",
							placeholder: "请输入",
							moduleKey: "noticeInterval",
							validate: function() {
								return [
									{
										validator: validateFormInt,
										trigger: "blur"
									}
								];
							}
						}
					],
					title: "报警信息"
				}
			]
		},
		/**
		 * @desc 编辑表格数据
		 * @param {Object} row 表格行数据
		 */
		async handleEdit(row) {
			this.openDialog();
			this.editInfo = row;
			// this.initForm()
			getAlarmInfoSetInfo({ id: row.id }).then(async (res) => {
				let values = [{}, {}, {}];
				let data = res.data.data;
				await this.changeSource("alarmType", data.alarmType);
				this.changeSource("enterprise", data.enterprise);
				if(data.conditionList.length){
					this.formList[1].list.length = 4;
				}
				this.formIndex = 0;
				for (
					let index = 0;
					index < data.conditionList.length;
					index++
				) {
					let v = data.conditionList[index];
					if (index > 0) {
						this.append();
					}
					for (const key in v) {
						data[key + "_" + index] = v[key];
						values[1][key + "_" + index] = v[key];
					}
				}
				const first = [
					"enterprise",
					"useSourceDevice",
					"alarmType",
					"alarmDelay"
				];
				const second = [
					"alarmDescribe",
					"continueAlarm",
					"noticeInterval"
				];
				first.forEach(v => {
					values[0][v] = data[v];
				});
				second.forEach(v => {
					values[2][v] = data[v];
				});
				this.$nextTick(() => {
					const parent = this.$refs.formDelg
						.getFormEle()
						.forEach((item, ide) => {
							item[0].setDefaultValue(values[ide]);
						});
				});
			});
		},
		/**
		 * @desc 新增、编辑数据
		 * @param {Object} formData 表单数据
		 */
		submit(formData) {
			formData.conditionList = JSON.stringify(formData.conditionList ?? []);
			formData.abnormalFactor = formData.alarmDescribe;
			if (this.editInfo.id) {
				this.update(formData);
			} else {
				InsertAlarmInfoSetInfo(formData).then(res => {
					if (res.code === 200) {
						this.closeDialog();
						this.getList();
						return this.$message({
							type: "success",
							message: "添加成功"
						});
					}
					return this.$message({
						type: "success",
						message: "添加失败"
					});
				});
			}
		},
		/**
		 * @desc 编辑数据
		 * @param {Object} params 表单数据
		 */
		update(params) {
			params.id = this.editInfo.id;
			UpdateAlarmInfoSetInfo(params).then(res => {
				if (res.code === 200) {
					this.closeDialog();
					this.getList();
					return this.$message({
						type: "success",
						message: "修改成功"
					});
				}
				return this.$message({
					type: "success",
					message: "修改失败"
				});
			});
		},
		/**
		 * @desc 表单联动函数
		 * @param {String} keys key
		 * @param {String} value 
		 */
		changeSource(keys, value) {
			// debugger
			if (keys === "enterprise") {
				const newForm = cloneDeep(this.formList);
				newForm[0].list[1] = {
					type: "select",
					label: "用源设备",
					width: "35%",
					labelWidth: "200px",
					placeholder: "",
					moduleKey: "useSourceDevice",
					children: "option",
					options: [],
					optionsType: {
						id: "id",
						label: "radUsedName"
					},
					query: {
						page: 1,
						limit: 1000,
						id: value
					},
					fetchTimes: Infinity,
					fetch: getUseSourceDeviceData,
					validate: function() {
						return [
							{
								required: true,
								message: "请选择用源设备",
								trigger: "blur"
							}
						];
					}
				};
				this.formList = newForm;
			}

			if (keys === "alarmType") {
				return this.$refs.formDelg.getFormEle()[0][0].getFormList('alarmType').then(res => {
					const objs = res.find(item => item.value === value);
					const {type, templateValue} = objs;
					let formIndex = 2;
					if(!templateValue){
						this.$message({
							type: 'warning',
							message: '请先给当前报警类型添加告警模板'
						})
					}
					if(type === 0){
						this.formList.splice(1,1,[])
						formIndex = 1;
						this.formIndex = 0;
						const forms = this.$refs.formDelg.getFormEle()[1][0].getFormData()
						this.$refs.formDelg.getFormEle()[1][0].deleteKeys( Object.keys(forms) );

					}
					if(type === 1){
						this.initForm()
					}
					this.$nextTick( () => {
						this.$refs.formDelg
						.getFormEle()
							[2][0].setDefaultValue({
								alarmDescribe: templateValue
							});
					})
				});
			}
		},
		/**
		 * @desc 点击树回调
		 * @param {Object} param 树节点数据
		 */
		treeHandle(param) {
			// this.enterpriseData = this.getEnterprise(param.nodes)
			this.enterpriseList = this.formList[0].list[0].options = this.getEnterprise(param.nodes);
			this.listQuery.nodeId = param.id;
			this.listQuery.nodeType = param.type;
			this.listQuery.treeType = param.treeType;
			this.getList();
		},
		/**
		 * @desc 获取企业节点
		 * @param {Object} nodes 树节点数据
		 * @param {Array} arr 企业数据集合
		 */
		getEnterprise(nodes, arr = []) {
			if (!Array.isArray(nodes.children) || !nodes.children.length)
				return arr;
			nodes.children.forEach(v => {
				if (v.type == "enterprise") {
					arr.push(v);
				} else {
					this.getEnterprise(v, arr);
				}
			});
			return arr;
		},
		/**
		 * @desc 关闭弹窗
		 */
		closeDialog() {
			this.$refs.formDelg.closeDialog();
		},
		onClose() {
			// this.initForm()
		},

		closed(){
			// this.$refs.formDelg.getFormEle().forEach(item => {
			// 	item[0].deleteKeys({id: ""})
			// });
		},
		/**
		 * @desc 打开弹窗
		 */
		openDialog() {
			this.editInfo = {};
			this.$refs.formDelg.openDialog();
		},
		/**
		 * @desc 新增表单行
		 */
		appendContent() {
			this.formIndex++;
			return [
				{
					type: "select",
					label: "报警因子",
					width: "23%",
					placeholder: "请输入",
					moduleKey: "alarmFactor_" + this.formIndex,
					children: "option",
					fetchTimes: Infinity,
					fetch: getMonitorObject,
					options: []
				},
				{
					type: "select",
					label: "条件",
					width: "23%",
					placeholder: "请输入",
					moduleKey: "condition_" + this.formIndex,
					children: "option",
					options: [
						{
							label: ">",
							value: ">"
						},
						{
							label: ">=",
							value: ">="
						},
						{
							label: "=",
							value: "="
						},
						{
							label: "<",
							value: "<"
						},
						{
							label: "<=",
							value: "<="
						}
					]
				},
				{
					type: "input",
					label: "值",
					width: "23%",
					placeholder: "请输入",
					moduleKey: "value_" + this.formIndex,
					validate: function() {
						return [
							{
								required: true,
								message: "请选择用源设备",
								trigger: "blur"
							},
							{ validator: validateFormNumber, trigger: "blur" }
						];
					}
				},
				{
					type: "select",
					label: "关联逻辑",
					width: "31%",
					labelWidth: "100px",
					placeholder: "请输入",
					moduleKey: "relat_" + this.formIndex,
					children: "option",
					after: {
						width: "36%",
						content: this.renderBtn1
					},
					options: [
						{
							label: "或",
							value: "或"
						},
						{
							label: "且",
							value: "且"
						}
					]
				}
			];
		},
		/**
		 * @desc 渲染表单新增行
		 * @param {Object} h 
		 * @param {Object} content 
		 */
		renderBtn(h) {
			return <div class="btn_wrap"></div>;
		},
		/**
		 * @desc 渲染表单新增行
		 * @param {Object} h 
		 * @param {Object} content 
		 */
		renderBtn1(h, content) {
			return (
				<div class="btn_wrap">
					<el-button
						size="mini"
						type="text"
						icon="el-icon-plus"
						on-click={() => this.append()}
					>
						添加
					</el-button>
					<el-button
						size="mini"
						type="text"
						style="color:red"
						icon="el-icon-delete"
						on-click={() => this.remove(content)}
					>
						删除
					</el-button>
				</div>
			);
		},
		/**
		 * @desc 渲染表单新增行
		 * @param {Object} h 
		 * @param {Object} content 
		 */
		renderBtn2(h, content) {
			return (
				<div class="btn_wrap">
					<el-button
						size="mini"
						type="text"
						style="color:red"
						icon="el-icon-delete"
						on-click={() => this.remove(content)}
					>
						删除
					</el-button>
				</div>
			);
		},
		/**
		 * @desc 渲染表单新增行
		 * @param {Object} h 
		 * @param {Object} content 
		 */
		renderBtn3(h) {
			return (
				<div class="btn_wrap">
					<el-button
						size="mini"
						type="text"
						icon="el-icon-plus"
						on-click={() => this.append()}
					>
						添加
					</el-button>
				</div>
			);
		},
		/**
		 * @desc 新增表单行回调
		 */
		append() {
			const listIndex = 1;
			const last = this.formList[listIndex].list.length - 1;
			if (last === 3) {
				this.formList[listIndex].list[
					last
				].after.content = this.renderBtn;
			} else {
				this.formList[listIndex].list[
					last
				].after.content = this.renderBtn2;
			}

			this.formList[listIndex].list.push(...this.appendContent());
		},
		/**
		 * @desc 删除表单行回调
		 */
		remove(c) {
			const listIndex = 1;
			let list = [];
			let delKeys = [];
			list = this.formList[listIndex].list.filter(v => {
				if (v.moduleKey.split("_")[1] === c.moduleKey.split("_")[1]) {
					delKeys.push(v.moduleKey);
				}
				return v.moduleKey.split("_")[1] != c.moduleKey.split("_")[1];
			});
			this.$refs.formDelg.getFormEle().forEach((item, inde) => {
				if (inde === 1) {
					item[0].deleteKeys(delKeys);
				}
			});
			const last = list.length - 1;
			if (last === 3) {
				list[last].after.content = this.renderBtn3;
			} else {
				list[last].after.content = this.renderBtn1;
			}
			this.formList[listIndex].list = list;
		},
		async getList() {
			this.listLoading = true;
			const { data } = await getAbnormalSurveyList(this.listQuery);
			this.total = data.total;
			this.tableData = data.abnormalSurveyList;
			this.listLoading = false;
		},
	}
};
</script>

<style lang="scss" scoped>
.alarminfo-config {
	/deep/ {
		.el-scrollbar__wrap {
			overflow-x: hidden;
		}
	}
}
</style>
